package com.sqlist.shareserver.resolver.impl;

import com.google.gson.reflect.TypeToken;
import com.sqlist.shareserver.connection.ConnectionPool;
import com.sqlist.shareserver.dto.LinkDTO;
import com.sqlist.shareserver.dto.MessageDTO;
import com.sqlist.shareserver.resolver.DataResolver;
import com.sqlist.shareserver.util.GsonUtils;
import com.sqlist.shareserver.util.TokenPool;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Type;

/**
 * Created by SqList on 2018/6/13.
 */

@Slf4j
@Component
public class LinkDTODataResolver implements DataResolver {

    @Autowired
    private ConnectionPool connectionPool;

    @Override
    public void resolve(String messageString, Channel channel) {
        log.debug("resolver()");
        Type type = new TypeToken<MessageDTO<LinkDTO>>(){}.getType();
        MessageDTO<LinkDTO> messageDTO = GsonUtils.getInstance().fromJson(messageString, type);

        String token = messageDTO.getToken();
        String username = messageDTO.getUsername();

        LinkDTO linkDTO = new LinkDTO();
        messageDTO.setData(linkDTO);
        if (TokenPool.contains(token)) {
            log.debug("TokenPool中存在 {} 的 {}", username, token);

            // 组装LinkDTO
            linkDTO.setStatus(LinkDTO.LINK_SUCCESS);
            messageDTO.setMsg("身份验证成功，上线");

            log.info("添加 {} 的  channel 到 connectionPool 中", username);
            connectionPool.addChannel(username, channel);
            log.info("{} 上线， token为 {}", username, token);
        } else {
            log.debug("TokenPool中不存在 {} 的 {}", username, token);

            // 组装
            linkDTO.setStatus(LinkDTO.LINK_FAIL);
            messageDTO.setMsg("身份验证失败");

            log.info("{} 上线失败", username);
        }

        // 发送消息
        byte[] req = (GsonUtils.getInstance().toJson(messageDTO) + "|").getBytes();
        ByteBuf byteBuf = Unpooled.buffer(req.length);
        byteBuf.writeBytes(req);
        channel.writeAndFlush(byteBuf);
    }
}
